package com.itheima.tlias.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.tlias.common.result.Result;
import com.itheima.tlias.mapper.ClazzMapper;
import com.itheima.tlias.pojo.dto.SelectClazzDTO;
import com.itheima.tlias.pojo.entity.Clazz;
import com.itheima.tlias.pojo.po.InsertClazzParam;
import com.itheima.tlias.pojo.po.SelectClazzPageParam;
import com.itheima.tlias.pojo.po.UpdateClazzParam;
import com.itheima.tlias.pojo.vo.PageBean;
import com.itheima.tlias.service.ClazzService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Resource
    private ClazzMapper clazzMapper;

    @Override
    public Result selectClazzByPage(SelectClazzPageParam param) {
        Page<Object> page = PageHelper.startPage(param.getPage(), param.getPageSize());
        List<SelectClazzDTO> list = clazzMapper.selectClazzByPage(param);
        PageBean<SelectClazzDTO> pageBean = new PageBean<>(page.getTotal(), list);
        return Result.success(pageBean);
    }

    @Override
    public Result insertClazz(InsertClazzParam param) {
        //name是否唯一
        Clazz clazz = clazzMapper.selectClazzByName(param.getName());
        if (Objects.isNull(clazz)) {
            return Result.error("班级名称");
        }
        param.setCreateTime(LocalDateTime.now());
        param.setUpdateTime(LocalDateTime.now());
        int clazzRows = clazzMapper.insertClazz(param);
        return clazzRows == 0 ? Result.error("添加班级失败") : Result.success();
    }

    @Override
    public Result selectClazzById(Integer id) {
        SelectClazzDTO dto = clazzMapper.selectClazzById(id);
        return Result.success(dto);
    }

    @Override
    public Result updateClazz(UpdateClazzParam param) {
        Clazz clazz = clazzMapper.selectClazzByName(param.getName());
        if (!Objects.equals(clazz.getId(), param.getId())) {
            return Result.error("班级名称重复");
        }
        param.setUpdateTime(LocalDateTime.now());
        int flag = clazzMapper.updateClazz(param);
        return flag == 0 ? Result.error("修改班级失败") : Result.success();
    }

    @Override
    public Result delectClazzById(Integer id) {
        int flag = clazzMapper.delectClazzById(id);
        return flag==0? Result.error("删除班级失败"): Result.success();
    }

    @Override
    public Result selectClazzAll() {
        List<SelectClazzDTO> dto = clazzMapper.selectClazzAll();
        return Result.success(dto);
    }
}
